import csv
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
import time
import datetime
import requests

def write_account(username, password):  # 写入账户
    with open("account.csv", 'a', newline="") as f:
        writer = csv.writer(f)
        writer.writerow([username, password])
        f.close()

def write_url(url):  # 写入网址
    with open("url.csv", 'a', newline="") as f:
        writer = csv.writer(f)
        writer.writerow([url])
        f.close()


def signin():  # 登录并记录
    global status
    status = 'success'
    username = []
    password = []
    with open("account.csv", "r", newline="") as f:#读取账户
        dataframe = csv.reader(f)
        next(dataframe)
        for i in dataframe:
            username.append(i[0])
            password.append(i[1])
        f.close()
    with open("url.csv", "r", newline="") as f:#读取校园网网址
        data = csv.reader(f)
        next(data)
        data = list(data)
        url = data[0][0]
        f.close()

    if not verify(url):
        status = 'fail'
        return 0
    else:
        driver_path = Service(r'msedgedriver.exe')
        driver = webdriver.Edge(service=driver_path)
        driver.get(url)  # 校园网登录网址
        driver.implicitly_wait(10)
        driver.find_element(By.XPATH, '//*[@id="username"]').send_keys(username)  # 找到账号输入框，并输入账号
        time.sleep(3)
        driver.find_element(By.XPATH, '//*[@id="pwd_tip"]').send_keys(password)  # 找到密码输入框，并输入密码
        time.sleep(3)
        driver.find_element(By.XPATH, '//*[@id="loginLink"]').click()  # 找到登录按钮，并点击
        try:
            driver.find_element(By.XPATH, '//*[@id="error_span_content"]')
            status = 'fail'
            return 1
        except:
            if verify('https://www.baidu.com'):
                None
            else:
                status = 'fail'
                return 2
        finally:
            driver.quit()
            t = datetime.datetime.now()
            with open("datatime.csv", "a", encoding="utf-8", newline="") as f:
                writer = csv.writer(f)
                writer.writerow([username, t, status])
                f.close()

def verify(url):#验证
    try:
        r = requests.get(url)
        return True
    except:
        return False

def csv_line(file):#计算csv行数
    l = 0
    with open(file, "r", newline="") as f:  # 读取
        dataframe = csv.reader(f)
        for row in dataframe:
            l += 1
        f.close()
    return l